package lolxxs.chenyanting.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

// 获取配置文件
@ConfigurationProperties("jwt.config")
@Component
public class JwtUtil {

    private String key;
    private long ttl;

    @Override
    public String toString() {
        return "JwtUtil{" +
                "key='" + key + '\'' +
                ", ttl=" + ttl +
                '}';
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public long getTtl() {
        return ttl;
    }

    public void setTtl(long ttl) {
        this.ttl = ttl;
    }

    // 根据id 和 userName生成token
    public String createJWT(String id, String userName, Integer identity) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(id)
                .setSubject(userName)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, key)
                .claim("access", "true")
                .claim("identity", identity);

        if (ttl > 0) {
            jwtBuilder.setExpiration(new Date(nowMillis + ttl));
        }

        return jwtBuilder.compact();
    }

    public Claims parseJWT(String jwtStr){
        return Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(jwtStr)
                .getBody();
    }
}
